#define _CRT_SECURE_NO_WARNINGS 1
#define _WINSOCK_DEPRECATED_NO_WARNINGS 2

#include <iostream>
#include <string>
#include <cstdlib>
#include <WinSock2.h>
#include <Windows.h>
#include <errno.h>
#include <io.h>
#include <fcntl.h>
#include <stdio.h>

#pragma comment(lib,"ws2_32.lib")

const int size = 4096;
const std::string ip = "47.122.50.102";
uint16_t port = 8080;

int main()
{
	WSADATA wsd;

	WSAStartup(MAKEWORD(2, 2), &wsd);

	struct sockaddr_in server;
	server.sin_port = htons(port);
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = inet_addr(ip.c_str());

	while (true)
	{
		SOCKET sockfd = socket(AF_INET, SOCK_STREAM, 0);
		if (sockfd < 0)
		{
			perror("socket error");
			return 0;
		}
		bool reconnet = false;
		int cnt = 5;
		do
		{
			int n = connect(sockfd, (struct sockaddr*)&server, sizeof(server));
			if (n < 0)
			{
				std::cout << "connect error , reconnect:" << cnt << std::endl;
				cnt--;
				reconnet = true;
			}
			else
			{
				break;
			}
		} while (reconnet && cnt);
		if (cnt == 0) {
			std::cout << "usersoff online" << std::endl;
			break;
		}
		(int)sockfd;
		char buffer[size];
		std::string msg;
		std::cout << "please enter@ ";
		std::getline(std::cin, msg);
		send(sockfd, msg.c_str(), msg.size(),0);
		int n = recv(sockfd, buffer, size - 1,0);
		if (n > 0)
		{
			buffer[n] = 0;
			std::cout << buffer << std::endl;
		}
		closesocket(sockfd);
	}
	return 0;
}

